/**
 * create by zhangpu
 * date:2015年3月12日
 */
package com.acooly.module.openapi.client.provider.webank.marshall;

import com.acooly.core.utils.Reflections;
import com.acooly.core.utils.Strings;
import com.acooly.module.openapi.client.api.anotation.ApiItem;
import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.api.message.MessageFactory;
import com.acooly.module.openapi.client.provider.webank.WeBankConstants;
import com.acooly.module.openapi.client.provider.webank.domain.WeBankNotify;
import com.acooly.module.openapi.client.provider.webank.enums.WeBankServiceEnum;
import com.acooly.module.openapi.client.provider.webank.partner.WeBankKeyPairManager;
import com.acooly.module.openapi.client.provider.webank.support.WeBankRespCodes;
import com.acooly.module.openapi.client.provider.webank.utils.SignUtils;
import com.acooly.module.safety.Safes;
import com.acooly.module.safety.signature.SignTypeEnum;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

/**
 * @author zhangpu
 */
@Service
public class WeBankNotifyUnmarshall extends WeBankMarshallSupport
        implements ApiUnmarshal<WeBankNotify, Map<String, String>> {
    private static final Logger logger = LoggerFactory.getLogger(WeBankNotifyUnmarshall.class);

    @Resource(name = "weBankMessageFactory")
    private MessageFactory messageFactory;

    @Resource(name = "weBankGetKeyPairManager")
    private WeBankKeyPairManager keyPairManager;

    @SuppressWarnings("unchecked")
    @Override
    public WeBankNotify unmarshal(Map<String, String> message, String serviceName) {
        try {
            logger.info("异步通知{}", message);
            String signature = message.get(WeBankConstants.SIGN);
            message.remove(WeBankConstants.SIGN);
            String plain = SignUtils.getSignContent(message);
            WeBankNotify weBankNotify = doUnmarshall(message, serviceName);
            //验签
            Safes.getSigner(SignTypeEnum.Rsa.name ()).verify(plain, keyPairManager.getKeyPair(weBankNotify.getPartnerId()), signature);
            return weBankNotify;
        } catch (Exception e) {
            throw new ApiClientException("异步通知 解析失败:" + e.getMessage());
        }
    }

    protected WeBankNotify doUnmarshall(Map<String, String> message, String serviceName) {
        WeBankNotify notify = (WeBankNotify) messageFactory.getNotify(serviceName);
        Set<Field> fields = Reflections.getFields(notify.getClass());
        String key = null;
        for (Field field : fields) {
            ApiItem apiItem = field.getAnnotation(ApiItem.class);
            if (apiItem != null && Strings.isNotBlank(apiItem.value())) {
                key = apiItem.value();
            }else {
                key = field.getName();
            }
            if(Strings.equals("merId",key)){
                notify.setPartnerId(message.get(key));
            }
            Reflections.invokeSetter(notify, field.getName(), message.get(key));
        }
        notify.setBizType(WeBankServiceEnum.find(serviceName).getCode());
        if (Strings.isNotBlank(notify.getRespCode())) {
            notify.setRespMsg(WeBankRespCodes.getMessage(notify.getRespCode()));
        }
        return notify;
    }

    public void setMessageFactory(MessageFactory messageFactory) {
        this.messageFactory = messageFactory;
    }

}
